import { util as cwUtil } from "../util";
import { Base64 } from "./base64.js";
import { util } from "./crypto.js";
import { HMAC } from "./hmac.js";
import { SHA1 } from "./sha1.js";
import API from "@/api";
import { md5 } from "js-md5";

const ossPrefixUrl = "https://recite-words.oss-cn-hangzhou.aliyuncs.com/";

const getOssParams = async (isLoading) => {
  const oss = await API.getSTSServer(isLoading);

  const policyText = {
    expiration: oss.Expiration,
    conditions: [
      ["content-length-range", 0, 1048576000], // 限制上传文件的大小，单位为字节，此处限制文件大小为1 GB。如果上传的文件大小超过此限制，文件将无法上传到OSS。如果未设置该限制，则默认文件大小最大为5 GB。
    ],
  };

  const policy = Base64.encode(JSON.stringify(policyText));
  const bytes = HMAC(SHA1, policy, oss.AccessKeySecret, { asBytes: true });
  const signature = util.bytesToBase64(bytes);

  return {
    policy,
    AccessKeyId: oss.AccessKeyId,
    SecurityToken: oss.SecurityToken,
    signature,
  }
}

export const ossDownLoad = async (filePath, hideLoading = true) => {
  const ossParams = await getOssParams();

  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: `${ossPrefixUrl}${filePath}`,
      header: {
        policy: ossParams.policy,
        OSSAccessKeyId: ossParams.AccessKeyId,
        "x-oss-security-token": ossParams.SecurityToken,
        success_action_status: "200",
        signature: ossParams.signature,
      },
      success: (res => {
        resolve({ success: true, data: res.tempFilePath });
      }),
      fail: () => {
        reject({ success: false, data: "下载失败" });
      },
      complete: () => {
        hideLoading && cwUtil.hideLoading();
      }
    })
  })
}

export const ossUpload = async (filePath, dir = "front-course/h5/", isLoading) => {
  const time = new Date().getTime();
  const idcode = uni.getStorageSync("idcode");
  const fileName = md5(`${idcode}, ${time}`) + ".wav";
  const key = dir + fileName;

  const ossParams = await getOssParams(isLoading);

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: ossPrefixUrl,
      filePath,
      name: "file",
      formData: {
        name: fileName,
        key,
        policy: ossParams.policy,
        OSSAccessKeyId: ossParams.AccessKeyId,
        "x-oss-security-token": ossParams.SecurityToken,
        success_action_status: "200",
        signature: ossParams.signature,
      },
      success: (res) => {
        resolve({
          success: true,
          data: {
            fileName: fileName,
          },
        });
      },
      fail: () => {
        reject({ success: false, data: "上传失败" });
      },
      complete: () => {
        cwUtil.hideLoading()
      }
    });
  });
};
